package com.xzq.socket.nio.client;

import lombok.Data;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/18 20:30
 * @Version 1.0.0
 **/
@Data
public class NioClient {
    private Selector selector;
    private SocketChannel socketChannel;
    private Charset charset;

    public NioClient() {
        try {
            selector = Selector.open();
            socketChannel= SocketChannel.open();
            socketChannel.configureBlocking(false);
            boolean isConnect = socketChannel.connect(new InetSocketAddress(9999));
            if (isConnect) {
                socketChannel.register(selector, SelectionKey.OP_READ);
            }else{
                socketChannel.register(selector, SelectionKey.OP_CONNECT);
            }
            new NioClientHandler(selector, Charset.forName("gbk")).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new NioClient();
    }
}
